#ifndef FILE_HANDLING_H
#define FILE_HANDLING_H

#include <ESP8266WebServer.h>
#include <LittleFS.h>
#include "led_control.h"
#include "mywifi_manager.h"


ESP8266WebServer esp8266_server(80);

// 前置声明
bool handleFileRead(String resource);
String getContentType(String filename);

void handleUserRequest() {
  String reqResource = esp8266_server.uri();
  Serial.print("reqResource: ");
  Serial.println(reqResource);

  bool fileReadOK = handleFileRead(reqResource);
  if (!fileReadOK) {
    esp8266_server.send(404, "text/plain", "哎呀，找不到你要的东西呢");
  }
}

bool handleFileRead(String resource) {
  if (resource.endsWith("/")) {
    resource = "/index.html";
  }

  String contentType = getContentType(resource);
  if (LittleFS.exists(resource)) {
    File file = LittleFS.open(resource, "r");
    esp8266_server.streamFile(file, contentType);
    file.close();
    return true;
  }
  return false;
}

String getContentType(String filename) {
  if (filename.endsWith(".htm") || filename.endsWith(".html"))
    return "text/html";
  else if (filename.endsWith(".css"))
    return "text/css";
  else if (filename.endsWith(".js"))
    return "application/javascript";
  else if (filename.endsWith(".png"))
    return "image/png";
  else if (filename.endsWith(".gif"))
    return "image/gif";
  else if (filename.endsWith(".jpg"))
    return "image/jpeg";
  else if (filename.endsWith(".ico"))
    return "image/x-icon";
  else if (filename.endsWith(".xml"))
    return "text/xml";
  else if (filename.endsWith(".pdf"))
    return "application/x-pdf";
  else if (filename.endsWith(".zip"))
    return "application/x-zip";
  else if (filename.endsWith(".gz"))
    return "application/x-gzip";
  return "text/plain";
}

void handlelocalIPset() {
  String localIP = esp8266_server.arg("ip");
  IPAddress local_IP_New;

  if (local_IP_New.fromString(localIP)) {
    if (WiFi.config(local_IP_New, gateway, subnet)) {
      Serial.println("IP地址配置成功");
      esp8266_server.sendHeader("Location", "/");
      esp8266_server.send(303);
    } else {
      Serial.println("IP地址配置失败");
      esp8266_server.send(500, "text/plain", "IP地址配置失败");
    }
  } else {
    Serial.println("无效的IP地址");
    esp8266_server.send(400, "text/plain", "无效的IP地址");
  }
}

void init_Server() {
  esp8266_server.on("/LED-Control", handleLEDControl);
  esp8266_server.on("/SET_LocalIP", handlelocalIPset);
  esp8266_server.onNotFound(handleUserRequest);
  esp8266_server.begin();
}

#endif
